package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.graphics.ColorUtils;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.GoodsListAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.im.IMUtils;
import com.zw.yzk.kabu.internal.component.DaggerStoreComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.CollectStoreModule;
import com.zw.yzk.kabu.internal.module.StoreModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.model.StoreModel;
import com.zw.yzk.kabu.presenter.StorePresenter;
import com.zw.yzk.kabu.utils.CircleTransform;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.view.view.StoreView;
import com.zw.yzk.refresh.library.PullToRefreshLayout;
import com.zw.yzk.refresh.library.RefreshBuilder;
import com.zw.yzk.refresh.library.State;
import com.zw.yzk.refresh.library.loadmore.DefaultLoadMoreViewCreator;
import com.zw.yzk.refresh.library.refrsh.DefaultRefreshViewCreator;

import skin.support.content.res.SkinCompatResources;

import javax.inject.Inject;

/**
 * Created by zhanwei on 2017/2/11.
 */

public class StoreActivity extends BaseActivity implements StoreView {

    @Bind(R.id.refresh_view)
    PullToRefreshLayout refreshLayout;
    @Bind(R.id.goods_list)
    RecyclerView goodsList;
    @Bind(R.id.tool_bar_title)
    TextView title;
    @Bind(R.id.navigation_bar)
    View toolBar;
    @Bind(R.id.right_image)
    CheckBox collect;
    private TextView name;
    private TextView phone;
    private ImageView topImage;
    private ImageView head;

    @Inject
    StorePresenter presenter;
    private GoodsListAdapter adapter;
    private int listScrollDistance;
    private int shopId;

    @Override
    public int getLayoutId() {
        PhoneUtils.setStatusBarTransparent(this);
        return R.layout.activity_store;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        PhoneUtils.setViewMarginTopStatusBarHeight(this, toolBar);
    }

    @Override
    public void initComponent() {
        DaggerStoreComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .storeModule(new StoreModule())
                .collectStoreModule(new CollectStoreModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecyclerView();
        getStoreInfo(0);
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected boolean skinStatusBarColorEnable() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getStoreInfoSuccess(StoreModel model) {
        setShopInfo(model.getShopInfo());
        adapter.add(model.getGoodsModel());
        refreshLayout.loadMoreFinish(model.getGoodsModel().isEmpty() ? State.LOAD_ALL : State.LOADING_SUCCEED);
    }

    @Override
    public void getStoreInfoFailed() {
        refreshLayout.finishRefreshingOrLoadingStatus(false);
    }

    @Override
    public boolean getCollectStatus() {
        return collect.isChecked();
    }

    @Override
    public void collectFiled() {
        setCollectStatus(!collect.isChecked());
    }

    @OnClick(R.id.back)
    public void back() {
        finish();
    }

    @OnClick(R.id.right_image)
    public void collectShop() {
        collectStore();
    }

    @OnClick(R.id.chat)
    public void startChartPage() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if(user == null || !user.isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        String ownerId = String.valueOf(getIntent().getIntExtra(ActivityConstant.STORE_OWNER_ID, -1));
        IMUtils.startPrivateConversationActivity(this, ownerId, name.getText().toString());
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        //初始化Header
        View header = LayoutInflater.from(this).inflate(R.layout.recycler_header_store, null);
        name = (TextView) header.findViewById(R.id.name);
        phone = (TextView) header.findViewById(R.id.phone);
        topImage = (ImageView) header.findViewById(R.id.top_bg);
        head = (ImageView) header.findViewById(R.id.head);

        goodsList.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        adapter = new GoodsListAdapter(null);
        goodsList.setAdapter(adapter);
        new RefreshBuilder.Builder(refreshLayout)
                .setHeader(header)
                .setRefreshEnable(false)
                .setRefreshViewCreator(new DefaultRefreshViewCreator())
                .setLoadMoreViewCreator(new DefaultLoadMoreViewCreator())
                .setRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        getStoreInfo(0);
                    }

                    @Override
                    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                        getStoreInfo(adapter.getItemCount());
                    }
                }).build();

        final int color = SkinCompatResources.getInstance().getColor(R.color.toolbar_bg);
        goodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                listScrollDistance += dy;
                float percent = listScrollDistance / (getResources().getDimension(R.dimen.toolbar_height) * 3f);
                percent = percent > 1 ? 1 : percent;

                int bgColor = ColorUtils.setAlphaComponent(color, (int) (255 * percent));
                toolBar.setBackgroundColor(bgColor);
                PhoneUtils.setStatusBarColor(StoreActivity.this, bgColor);
            }
        });
    }

    /**
     * 设置店铺基本信息
     *
     * @param info
     */
    private void setShopInfo(StoreModel.ShopInfo info) {
        if (info == null) {
            return;
        }
        shopId = info.getShopId();

        setCollectStatus(info.getCollected());
        title.setText(info.getShopName());
        name.setText(info.getShopOwnerName());
        phone.setText(info.getOwnerPhone());
        Glide.with(this)
                .load(info.getShopImage())
                .into(topImage);
        Glide.with(this)
                .load(info.getImage())
                .transform(new CircleTransform(this))
                .error(R.drawable.ic_default_head)
                .into(head);
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StoreActivity.this, HomePageActivity.class);
                intent.putExtra(ActivityConstant.HOME_PAGE_ID, getIntent().getIntExtra(ActivityConstant.STORE_OWNER_ID, -1));
                startActivity(intent);
            }
        });
    }

    /**
     * 设置收藏按钮状态
     *
     * @param checked
     */
    private void setCollectStatus(boolean checked) {
        collect.setChecked(checked);
    }

    /**
     * 获取商店详情
     *
     * @param start
     */
    private void getStoreInfo(int start) {
        presenter.getStoreInfo(getIntent().getIntExtra(ActivityConstant.STORE_OWNER_ID, -1), start);
    }

    /**
     * 关注或者取消关注
     */
    private void collectStore() {
        presenter.collectStore(shopId, collect.isChecked());
    }

}
